﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Preyla
{
    public partial class FormSystem : Form
    {
        int Rights;

        IDatabase DBManager = new AccessManager(Properties.Settings.Default.ConnectionString);

        List<int> DeletedComponents = new List<int>();
        List<IDNamePair> Components = new List<IDNamePair>();

        string SystemName;
        int ConfigurationID;
        int ServerID;

        public FormSystem(int ServerID, int ConfigurationID, string SystemName, int Rights)
        {
            InitializeComponent();

            this.ServerID = ServerID;
            this.ConfigurationID = ConfigurationID;
            this.SystemName = SystemName;

            this.Text = SystemName;

            this.Rights = Rights;
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void FormSystem_FormClosing(object sender, FormClosingEventArgs e)
        {
            bool b = Save();

            if (!b)
            {
                DialogResult dialogResult = MessageBox.Show("There are errors during saving. Quit without saving?", "Warning", MessageBoxButtons.YesNo);

                if (dialogResult == DialogResult.Yes)
                {
                    DBManager.Close();
                }
                else
                {
                    e.Cancel = true;
                }
            }
        }

        private void FormSystem_Load(object sender, EventArgs e)
        {
            DBManager.Open();

            FillComponents();

            for (int i = 0; i < Components.Count; i++)
            {
                ServerComponent.Items.Add(Components[i].Name);
            }

            Read();

            if (Rights == 2)
            {
                //SystemTable.AllowUserToAddRows = false;
                SystemTable.AllowUserToDeleteRows = false;
                SystemTable.ReadOnly = true;
            }
        }

        void FillComponents()
        {
            string[][] Data = DBManager.ExecuteReader("SELECT DISTINCT Objects.ID, [Name] FROM Objects, Links WHERE Objects.ID=Links.ID AND (Links.Duplication <> 0 OR Links.Duplication IS NULL) UNION SELECT Objects.ID, [Name] FROM Objects WHERE NOT EXISTS (SELECT ID FROM Links WHERE Links.ID = Objects.ID);");
            //string[][] Data = DBManager.ExecuteReader("SELECT Objects.ID, Name FROM Objects WHERE NOT EXISTS (SELECT ID FROM Links WHERE Links.ID = Objects.ID);");

            for (int i = 0; i < Data.Length; i++)
            {
                Components.Add(new IDNamePair(Int32.Parse(Data[i][0]), Data[i][1]));
            }
        }

        void Read()
        {
            string[][] Data = DBManager.ExecuteReader("SELECT Components.ID, Components.[Name], CompConfLink.Duplication, CompConfLink.LinkID FROM Objects Components, Links CompConfLink, Objects Configurations WHERE Components.ID = CompConfLink.ObjectID AND CompConfLink.ID = Configurations.ID AND Configurations.ID = " + ConfigurationID + ";");

            for (int i = 0; i < Data.Length; i++)
            {
                SystemTable.Rows.Add();
                SystemTable[0, SystemTable.Rows.Count - 2].Value = Data[i][3];
                (SystemTable[1, SystemTable.Rows.Count - 2] as DataGridViewComboBoxCell).Value = Data[i][1];
                SystemTable[2, SystemTable.Rows.Count - 2].Value = Data[i][2];
            }
        }

        bool Save()
        {
            for (int i = 0; i < SystemTable.Rows.Count - 1; i++)
            {
                try
                {
                    if (SystemTable[1, i].Value == null)
                    {
                        MessageBox.Show("Component is not selected");

                        return false;
                    }

                    if (SystemTable[2, i].Value == null)
                    {
                        MessageBox.Show("Duplication is empty");

                        return false;
                    }   

                    int Duplication;

                    try
                    {
                        Duplication = Int32.Parse(SystemTable[2, i].Value.ToString());
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Duplication is not a number");

                        return false;
                    }

                    if (Duplication <= 0)
                    {
                        MessageBox.Show("Duplication must be greater than 0");

                        return false;
                    }

                    int ComponentID = -1;

                    for (int j = 0; j < Components.Count; j++)
                    {
                        if (Components[j].Name.CompareTo(SystemTable[1, i].Value) == 0)
                        {
                            ComponentID = Components[j].ID;

                            break;
                        }
                    }

                    if (SystemTable[0, i].Value != null)
                    {
                        DBManager.ExecuteNonQuery(String.Format("UPDATE Links SET ObjectID={3}, Duplication={0} WHERE LinkID = {1} AND ID = {2};", Duplication, SystemTable[0, i].Value, ConfigurationID, ComponentID));
                    }
                    else
                    {
                        DBManager.ExecuteNonQuery(String.Format("INSERT INTO Links (ID, ObjectID, Duplication) VALUES ({0}, {1}, {2})", ConfigurationID, ComponentID, SystemTable[2, i].Value));
                        SystemTable[0, i].Value = 0;

                    }
                }
                catch (Exception ex)
                { }
            }

            for (int i = 0; i < DeletedComponents.Count; i++)
            {
                DBManager.ExecuteNonQuery("DELETE FROM Links WHERE LinkID = " + DeletedComponents[i]);
            }

            DeletedComponents.Clear();

            return true;
        }

        private void SystemTable_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            try
            {
                if (MessageBox.Show("Delete row?", "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    DeletedComponents.Add(Int32.Parse(SystemTable[0, e.Row.Index].Value.ToString()));
                }
                else
                {
                    e.Cancel = true;
                }                 
            }
            catch (Exception ex)
            { }  
        }
    }
}
